<template>
  <div class="controller">
    <p>管理者信息</p>
    <el-form :model="list" class="header">
      <!-- <el-form-item label="管理者编号" style="width: 200px">
            <el-input v-model="list.id" placeholder="请输入编号" type="text">
            </el-input>
          </el-form-item> -->
      <el-form-item label="名字" style="width: 200px">
        <el-input v-model="list.position" placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item class="btn">
        <el-button type="primary" @click="searchP">查询</el-button>
        <el-button type="success" @click="dialogVisible2 = true">添加</el-button>
        <el-button :icon="Download" class="100px" @click="handledownload"
          style="background-color: #9e83f8;color: #fff;" />
      </el-form-item>
    </el-form>
    <el-table :data="showList" style="width: 100%;">
      <!-- <el-table-column type="index" label="序号" width="80" /> -->
      <el-table-column label="ID" prop="id" />
      <el-table-column label="用户姓名" prop="name" />
      <el-table-column label="用户名" prop="username" />
      <el-table-column label="性别" prop="sex" />
      <el-table-column label="地址" prop="role" />
      <el-table-column label="联系方式" prop="phone" />
      <el-table-column fixed="right" label="操作" width="200">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">修改</el-button>
          
          <el-popconfirm title="你确定要删除他吗？" @confirm="deleteP(scope.row)">
    <template #reference>
      <el-button type="danger" size="small" >删除</el-button>
    </template>
  </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 删除确认框 -->
    <el-dialog v-model="dialogVisible" title="提示" width="30%">
      <span>是否删除此管理员</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handrevess">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 添加弹出框 -->
    <el-dialog v-model="dialogVisible2" title="添加管理者" width="40%">
      <el-form label-width="200px" :rules="rules">
        <el-col :span="24">
          <el-form-item label="用户姓名" label-width="100px" prop="name">
            <el-input v-model="newPerson.name" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="用户名" label-width="100px" prop="username">
            <el-input v-model="newPerson.username" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="用户地址" label-width="100px" prop="role">
            <el-input v-model="newPerson.role" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="用户性别" label-width="100px" prop="sex">
            <el-select v-model="newPerson.sex" placeholder="请选择性别">
              <el-option label="女" value="女" />
              <el-option label="男" value="男" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="联系方式" label-width="100px" prop="phone">
            <el-input v-model="newPerson.phone" />
          </el-form-item>
        </el-col>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addProductDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addEvt">保存</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 修改框 -->
    <el-dialog v-model="dialogFormVisible" title="修改管理者信息" width="40%">
      <el-form label-width="200px" :rules="rules">
        <el-col :span="24">
          <el-form-item label="客户姓名" label-width="100px" prop="name">
            <el-input v-model="editPerson.info.name" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="用户名" label-width="100px" prop="username">
            <el-input v-model="editPerson.info.username" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="用户地址" label-width="100px" prop="username">
            <el-input v-model="editPerson.info.role" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="管理员性别" label-width="100px" prop="sex">
            <el-select v-model="editPerson.info.sex" placeholder="请选择性别">
              <el-option label="女" value="女" />
              <el-option label="男" value="男" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="联系方式" label-width="100px" prop="phone">
            <el-input v-model="editPerson.info.phone" />
          </el-form-item>
        </el-col>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave(editPerson.info.id)">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang= "ts" setup>
import { computed, onMounted, ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { utils, writeFileXLSX } from 'xlsx'
import { Download } from '@element-plus/icons-vue'
import { getState } from '../../api/state'

const showList: any = ref([])
let List: any = ref([])
// const dialogVisible2 = ref(false)
const newPerson = reactive({
  id: Date.now() + '',
  name: '',
  username: '',
  role: '',
  sex: '',
  phone: ''
})
let editPerson = reactive({
  info: {
    id: '',
    name: '',
    username: '',
    role: '',
    sex: '',
    phone: ''
  }

})
function addEvt() {
  dialogVisible2.value = false
  const userList = {
    id: newPerson.id,
    name: newPerson.name,
    username: newPerson.username,
    role: newPerson.role,
    sex: newPerson.sex,
    phone: newPerson.phone,
  }
  List.value = showList.value = false?[]:showList.value
  List.value.push(userList)
  console.log(List.value);

  newPerson.id = Date.now() + ''
  newPerson.name = ''
  newPerson.username = ''
  newPerson.role = ''
  newPerson.sex = ''
  newPerson.phone = ''
  localStorage.setItem('clientList', JSON.stringify(List.value))
  showList.value = JSON.parse(localStorage.getItem('clientList'))
  console.log(showList.value);
}
onMounted(() => {
  if(!JSON.parse(localStorage.getItem('clientList'))){
    localStorage.setItem('clientList', JSON.stringify([]))
  }
  showList.value = JSON.parse(localStorage.getItem('clientList'))
})

function deleteP(row:any) {
  console.log(row.id);
  let list = JSON.parse(localStorage.getItem('clientList'))
  list.forEach((it,i) => {
    if(it.id == row.id) {
      console.log(i);
      list.splice(i,1)
      console.log(showList.value);
    }
  })
  localStorage.setItem('clientList', JSON.stringify(list))
  showList.value = JSON.parse(localStorage.getItem('clientList'))
}
function searchP() {
  console.log(list.position);
  showList.value = JSON.parse(localStorage.getItem('clientList'))
  showList.value = showList.value.filter(it => it.name.includes(list.position))
}
// 订单状态数据
const loadState = async () => {
  const result = await getState()
  console.log(result)
}
loadState()
const dialogVisible2 = ref(false)
const dialogVisible = ref(false) // 删除
// 查询
const search = ref('')

// 添加
const addProductDialogVisible = ref(false)
const newProduct = ref<Partial<TableData>>({})

// 修改
const reviseProduct = ref<any>();
const dialogFormVisible = ref(false)
// 数据格式
interface TableData {
  id: number;
  address: null | string;
  itemCount: number;
  itemInfo: string;
  itemPrice: number | number;
  notes: string;
  orderCreateTime: string;
  orderNo: string;
  productId: number;
  sigPrice: null;
  status: number;
  userId: number;
}
const tableData = ref([
  {
    "id": 62,
    "userId": 27,
    "productId": 66,
    "orderNo": "sit exercitation in in",
    "status": 97,
    "itemInfo": "eiusmod deserunt exercitation",
    "itemCount": 58,
    "sigPrice": null,
    "itemPrice": 56,
    "notes": "deserunt",
    "address": "上海滨州市青县",
    "orderCreateTime": "1975-09-28 09:16:34"
  }
])
const list = reactive({
  id: '',
  position: '',
  date: '',
})
// 查询
const filterTableData = computed(() =>
  tableData.value.filter(
    (data) =>
      !search.value ||
      data.id.toLowerCase().includes(search.value.toLowerCase())
  )
)
// 表单校验规则
// const rules = reactive({
//   name: [
//     { required: true, message: '请输入姓名', trigger: 'blur' },
//     { min: 2, max: 20, message: '长度为2-20', trigger: 'blur' },
//   ],
//   username: [
//     { required: true, message: '请输入用户名', trigger: 'blur' },
//     { min: 2, max: 20, message: '长度为2-20', trigger: 'blur' },
//   ],
//   role: [
//     {
//       required: true,
//       message: '请选择职位',
//       trigger: 'change',
//     },
//   ],
//   sex: [
//     {
//       required: true,
//       message: '请选择性别',
//       trigger: 'change',
//     },
//   ],
//   phone: [
//     { required: true, message: '请输入练习方式', trigger: 'blur' },
//     { min: 11, max: 11, message: '长度为11位', trigger: 'blur' },
//   ],
// })
// 添加
const handleAdd = () => {
  addProductDialogVisible.value = true;
}
const addProduct = () => {
  console.log(newPerson);
}

let nowp: any = ref([])
// 修改

let gaiPerson = reactive({
  name: '',
  username: '',
  role: '',
  sex: '',
  phone: ''
})
const handleEdit = (row) => {
  let info = {}
  console.log('修改', row.id);
  console.log('1', editPerson.info);
  editPerson.info = JSON.parse(JSON.stringify(row))
  console.log('2', editPerson.info);
  console.log(editPerson.info);
  dialogFormVisible.value = true;
}
const handleSave = (id) => {
  showList.value.forEach((it, i) => {
    if (it.id == id) {
      console.log(showList.value[i]);
      showList.value[i] = editPerson.info
      console.log('22222',showList.value[i]);
    }
  });
  console.log('修改后',editPerson.info);
  const userList = {
    id: newPerson.id,
    name: newPerson.name,
    username: newPerson.username,
    role: newPerson.role,
    sex: newPerson.sex,
    phone: newPerson.phone,
  }
  List.value = showList.value
  console.log(List.value);
  localStorage.setItem('clientList', JSON.stringify(List.value))
  showList.value = JSON.parse(localStorage.getItem('clientList'))

  dialogFormVisible.value = false;
}

// 删除
const delateId = ref('1234')
const handleDelete = (row: any) => {
  console.log('删除');
  delateId.value = row.id;
  dialogVisible.value = true;
}
// 删除逻辑
const handrevess = () => {
  tableData.value = tableData.value.filter((item: any) => item.id !== delateId.value)
  console.log(tableData.value);


  dialogVisible.value = false;

}
// 禁用
const doAllow = (row: any) => {
  row.status = !row.status

}
//导出文件
const handledownload = () => {
  // 将待导出数据转换为 sheet 工作表中要使用到的数据，并生成工作表
  const ws = utils.json_to_sheet(showList.value)
  // 创建新工作簿
  const wb = utils.book_new()
  // 将工作表追加到工作簿中
  utils.book_append_sheet(wb, ws, '管理者列表详情表')
  // 将内存中的工作簿数据写入文件中
  console.log(ws, wb)
  writeFileXLSX(wb, `table-${new Date().toISOString()}.xlsx`)
  console.log('data:')
}
// 性别自动补全框
interface RestaurantItem {
  value: string
}
const restaurants = ref<RestaurantItem[]>([])
const querySearch = (queryString: string, cb: any) => {
  const results = queryString
    ? restaurants.value.filter(createFilter(queryString))
    : restaurants.value
  // call callback function to return suggestions
  cb(results)
}
const createFilter = (queryString: string) => {
  return (restaurant: RestaurantItem) => {
    return (
      restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    )
  }
}

const loadAll = () => {
  return [
    { value: '男' },
    { value: '女' },
  ]
}

// onMounted(() => {
//   restaurants.value = loadAll()
// })
</script>

<style lang= "less" scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.btn {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 200px;
  height: 50px;
}

::v-deep .el-form-item__content {
  flex-wrap: nowrap;
}

.el-input {
  width: 200px;
  margin-right: 10px;
}</style>